<template>
  <div class="plot-panel">
    <el-tabs v-model="activeName" style="height: 100%;padding:2px 4px">
      <el-tab-pane label="符号库" name="first">
        <div class="plot-symbol">
          <el-row v-for="row in rows" :key="row.id">
            <el-col v-for="s in row.data" :span="6" :key="s.id">
              <div class="card" @click="onSymbolSelected(s)">
                <plot-symbol
                  :flag="s.flag"
                  :line-width="s.lineWidth"
                  :stroke-style="s.strokeStyle"
                  :fill-style="s.fillStyle"
                  :scale="s.scale"
                  :active="isSelected === s._id"
                  :url="s.url"
                  :name="s.name"
                />
              </div>
            </el-col>
          </el-row>
        </div>
      </el-tab-pane>
      <el-tab-pane label="档案" name="second">
        <div id="militaryarchives">
          <div class="militaryarchives">
            <el-button size="small" icon="kfb-icon-wenjianguanli" @click="newArchives">新建档案组</el-button>
            <el-button size="small" icon="kfb-icon-shanchu1" @click="clearAll">清空标绘</el-button>
          </div>
          <div style="height: 700px">
            <el-scrollbar class="plot-panel-component__scroll">
              <el-tree
                :data="dataArchives"
                :expand-on-click-node="false"
                node-key="aid"
                default-expand-all
                icon="kfb-icon-yonghuzu"
                @node-click="archiveClick"
              >
                <span slot-scope="{node, data}" class="custom-tree-node">
                  <span>
                    <i
                      v-if="node.key!==currentSelectArchiveKey"
                      :class="data.children ?'kfb-icon-wenjianguanli':'kfb-icon-kehuxinxiliebiao'"
                    >{{ data.label }}</i>
                    <el-input
                      v-else
                      id="selectarchive"
                      :id="node.key"
                      v-model="data.label"
                      @keyup.enter.native="submitArchiveEdit(node)"
                      @keyup.esc.native="cancelArchiveEdit()"
                    />
                  </span>
                  <span>
                    <el-tooltip class="item" effect="light" content="Enter确认，ESC取消" placement="top">
                      <el-button
                        icon="el-icon-edit"
                        type="text"
                        size="mini"
                        @click.stop="modifyArchives(node, data)"
                      />
                    </el-tooltip>
                    <el-button
                      v-if="!data.features"
                      icon="el-icon-circle-plus-outline"
                      type="text"
                      size="mini"
                      @click.stop="addArchive(node, data)"
                    />
                    <el-button
                      icon="el-icon-remove-outline"
                      type="text"
                      size="mini"
                      @click.stop="removeArchivesOrArchive(node, data)"
                    />
                  </span>
                </span>
              </el-tree>
            </el-scrollbar>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import Vue from 'vue'
import { mapState } from 'vuex'
import PlotSymbol from '@/components/PlotSymbol'
import { list } from '@/api/yxwh/bhfh'
import { uuid } from '@/assets/js/utils/Uuid'
import { listArchives, saveArchives, removeArchives } from '@/api/yzt'
import TextPlot from '@/pages/yzt/components/text'
export default {
  name: 'Index',
  components: { PlotSymbol, TextPlot },
  data() {
    return {
      isSelected: undefined,
      activeName: 'first',
      dataArchives: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      setting: undefined,
      currentSelectArchiveKey: -1,
      popLeft: undefined,
      popRight: undefined,
      plotLngLat: undefined,
      plotTextMarkers: [],
      // plotTextMarkersRight: [],
      isPlotText: undefined
    }
  },
  methods: {
    onSymbolSelected(s) {
      // 保存选中的符号
      this.isSelected = s._id
      this.mapServiceRight.setSelectSymbol(s)
      this.isPlotText = false
      // 设置标绘模式
      switch (s.type) {
        case 0:
          this.mapServiceRight.setChangeMode('draw_point')
          // this.mapServiceLeft.setChangeMode("draw_point");
          break
        case 1:
          this.mapServiceRight.setChangeMode('draw_line_string')
          // this.mapServiceLeft.setChangeMode("draw_line_string");
          break
        case 2:
          this.mapServiceRight.setChangeMode('draw_polygon')
          // this.mapServiceLeft.setChangeMode("draw_polygon");
          break
        case 3: // 文本
          this.isPlotText = true
          break
        case 4: // 直箭头
          this.mapServiceRight.setChangeMode('draw_straightArrow')
          //  this.mapService.setChangeMode('draw_CutLineMode');
          break
        case 5: // 斜箭头
          this.mapServiceRight.setChangeMode('draw_DiagonalArrow')
          break
        case 6: // 燕尾箭头
          this.mapServiceRight.setChangeMode('draw_DoveTailStraightArrow')
          break
        case 7: // 燕尾斜箭头
          this.mapServiceRight.setChangeMode('draw_DoveTailDiagonalArrow')
          break
        case 8: // 双箭头
          this.mapServiceRight.setChangeMode('draw_DoubleArrow')
          break
      }
    },
    /**
     * 创建DIVmarker
     */
    createdDivMarker(text, style, coord) {
      const el = document.createElement('div')
      el.innerHTML = text
      el.style.fontSize = style.fontSize
      el.style.color = style.color
      el.style.fontWeight = style.fontWeight
      el.style.fontStyle = style.fontStyle
      return new mapboxgl.Marker(el, {
        offset: [35, 15],
        draggable: true
      }).setLngLat(coord)
    },

    // 确定
    onConfirm(text, style) {
      const map = this.mapServiceRight.getMap()
      const currentMarkerTitleRight = this.createdDivMarker(
        text,
        style,
        this.plotLngLat
      ).addTo(map)
      this.plotTextMarkers.push(currentMarkerTitleRight)
      this.popRight.remove()
      this.isPlotText = false
    },
    /**
     * 新建档案
     */
    addArchive(node, data) {
      const markers = []
      for (let i = 0; i < this.plotTextMarkers.length; i++) {
        const m = this.plotTextMarkers[i]
        markers.push({
          html: m.getElement().innerHTML,
          style: {
            fontSize: m.getElement().style.fontSize,
            fontWeight: m.getElement().style.fontWeight,
            color: m.getElement().style.color,
            fontStyle: m.getElement().style.fontStyle
          },
          coord: m.getLngLat()
        })
      }
      const features = this.mapServiceRight.getDrawControlFC()
      const map = this.mapServiceRight.getMap()
      const newChild = {
        aid: uuid(),
        label: '新建档案',
        center: map.getCenter(),
        zoom: map.getZoom(),
        features: features,
        textMarkers: markers
      }

      data.children.push(newChild)
      // 发起请求
      this.updateArchives(data)
    },
    /**
     * 新建档案组
     */
    newArchives() {
      const newChild = {
        aid: uuid(),
        label: '新建档案组',
        children: [],
        uid: this.$store.getters.id
      }
      this.dataArchives.push(newChild)
      this.updateArchives(newChild)
    },
    /**
     *
     * 清除
     */
    clearAll() {
      // 清空文本信息
      for (let i = 0; i < this.plotTextMarkers.length; i++) {
        this.plotTextMarkers[i].remove()
        // this.plotTextMarkersRight[i].remove();
      }
      this.plotTextMarkers = []
      // this.plotTextMarkersRight = [];
      // 清空标绘
      this.mapServiceRight.setDrawControlFC({
        type: 'FeatureCollection',
        features: []
      })
    },

    /**
     * 修改档案名称
     * @param node 修改的当前档案节点
     * @param data 修改的当前档案数据
     */
    modifyArchives(node, data) {
      this.currentSelectArchiveKey = node.key
    },
    /**
     * 删除档案
     * @param node 要删除的当前档案节点
     * @param data 要删除的当前档案数据
     */
    removeArchivesOrArchive(node, data) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 判断删除子节点还是父节点，如果是子节点 更新，父节点 删除
          const parent = node.parent
          const children = parent.data.children || parent.data
          const index = children.findIndex(d => d._id === data._id)
          const del = children.splice(index, 1)
          if (Array.isArray(parent.data)) {
            // 删除父节点
            removeArchives({ id: del[0]._id }).then(res => {})
          } else {
            // 删除子节点
            this.updateArchives(parent.data)
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    /**
     * 确认修改档案名称
     * @param data
     */
    submitArchiveEdit(node) {
      if (node.level === 1) {
        this.currentSelectArchiveKey = -1
        this.updateArchives(node.data)
      }
      if (node.level === 2) {
        this.currentSelectArchiveKey = -1
        this.updateArchives(node.parent.data)
      }
    },
    /**
     * 取消修改档案名称
     */
    cancelArchiveEdit() {
      this.currentSelectArchiveKey = -1
    },
    /**
     * 更新档案
     * @param id
     * @param archives
     */
    updateArchives(archives) {
      saveArchives(archives).then(res => {})
    },

    /**
     * 点击档案,显示档案内容
     */
    archiveClick($event) {
      this.clearAll()
      if ($event.features) {
        this.mapServiceRight.setDrawControlFC($event.features)
        this.mapServiceRight.flyTo(
          { type: 'Point', coordinates: $event.center },
          $event.zoom
        )
      }

      if ($event.textMarkers) {
        const map = this.mapServiceRight.getMap()
        for (let i = 0; i < $event.textMarkers.length; i++) {
          const data = $event.textMarkers[i]
          const currentMarkerTitleRight = this.createdDivMarker(
            data.html,
            data.style,
            [data.coord.lng, data.coord.lat]
          ).addTo(map)
          this.plotTextMarkers.push(currentMarkerTitleRight)
        }
      }
    },

    /**
     * 获取档案数据
     */
    getArchiveData() {
      listArchives({ uid: this.$store.getters.id }).then(res => {
        this.dataArchives = res.data
      })
    },
    /**
     *
     * 选择事件
     * @param map
     * @param e
     * @param id
     */
    mapClickEvent(e) {
      if (!this.isPlotText) {
        return
      }
      const map = this.mapServiceRight.getMap()
      this.plotLngLat = [e.lngLat.lng, e.lngLat.lat]
      // this.popLeft.setLngLat(this.plotLngLat).addTo(map);
      this.popRight.setLngLat(this.plotLngLat).addTo(map)
    }
  },
  computed: {
    ...mapState({
      mapServiceRight(state) {
        return state.eswyzt.mapServiceRight
      },
      mapServiceLeft(state) {
        return state.eswyzt.mapServiceLeft
      },
      symbols(state) {
        return state.eswyzt.symbols
      }
    }),
    rows() {
      const rows = []
      if (!this.symbols) {
        return rows
      }
      const row = Math.ceil(this.symbols.length / 4)
      for (var i = 0; i < row; i++) {
        const start = i * 4
        const end = (i + 1) * 4
        rows.push({
          id: i,
          data: this.symbols.slice(
            start,
            end > this.symbols.length ? this.symbols.length : end
          )
        })
      }

      return rows
    },

    // 地图初始化
    onMapInit(right) {}
  },
  mounted() {
    this.setting = new Vue({
      render: h =>
        h(TextPlot, {
          on: {
            onConfirm: this.onConfirm
          }
        })
    })

    this.popRight = new mapboxgl.Popup({
      closeOnClick: false,
      closeButton: true
    }).setDOMContent(this.setting.$mount().$el)
    this.bus.$on('onMapInit', right => {
      this.getArchiveData()
      right.on('click', this.mapClickEvent, this)
    })
  },
  beforeDestroy() {
    this.mapServiceRight.off('click', this.mapClickEvent)
  }
}
</script>

<style>
.plot-panel {
  color: #fff;
  height: 100%;
}
.plot-panel .plot-panel-component__scroll {
  height: 100%;
}
.plot-panel .plot-panel-component__scroll .el-scrollbar__wrap {
  overflow-x: auto;
}
.plot-panel #militaryarchives .el-tree {
  background-color: #0000;
  color: #fff;
  font-size: 0.5em;
}
.plot-panel .sys-symbol {
  border: 1px solid #ffffff00;
}

.plot-panel .sys-symbol .name {
  color: #fff;
}

.plot-panel .plot-symbol {
  height: auto;
  width: 100%;
}

.plot-panel .card {
  text-align: center;
  padding: 5px;
}

.plot-panel .card:hover {
  cursor: pointer;
}

.plot-panel .card div {
  font-size: 1px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}

.plot-panel .plot-symbol .box img {
  margin-bottom: 3px;
  display: block;
}

#militaryarchives .el-button {
  background-color: #ffffff00;
  color: white;
  margin-right: 1em;
}

#militaryarchives .el-button:hover {
  color: #398f86ff;
  border-color: #398f86ff;
}

#militaryarchives .custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

#militaryarchives .kfb-icon-wenjianguanli:before {
  padding-right: 0.6em;
}

#militaryarchives .kfb-icon-kehuxinxiliebiao:before {
  padding-right: 0.6em;
}

#militaryarchives .kfb-icon-shanchu1:before {
  padding-right: 0.6em;
}

#militaryarchives [class^="el-icon"] {
  color: #fff;
}

#militaryarchives .el-tree-node > .el-tree-node__content:hover {
  background-color: #00000043;
}

#militaryarchives .el-tree-node:focus > .el-tree-node__content {
  background-color: #00000043;
}

#militaryarchives [class^="kfb-icon"],
[class*=" kfb-icon"] {
  font-size: 1.1em;
  font-family: Menlo, Monaco, Consolas, "Courier New", monospace;
}

.plot-panel .el-tabs__item.is-active {
  font-size: 16px;
  color: #fff;
}

/* .plot-panel .sys-symbol:hover {
  cursor: pointer;
  background-color: #e5e5e500;
  border: 1px solid #398f86;
}

.plot-panel .sys-symbol-active {
  background-color: #d4d4d400;
  border: 1px solid #398f86;
} */

#militaryarchives .militaryarchives {
  margin: 0 0 10px 0;
  text-align: right;
}

.plot-panel .el-tabs__item {
  font-size: 16px;
  color: #fff;
}

.plot-panel .el-tabs__item.is-active {
  font-size: 16px;
  color: #fff;
}

.plot-panel .el-tabs__active-bar {
  background-color: #398f86ff;
}

.plot-panel .el-tabs__item:hover {
  font-size: 16px;
   color: #398f86FF;
}
.plot-panel .plot-panel-component__scroll .el-input__inner {
  background: transparent;
  height: 30px;
  line-height: 30px;
}
</style>

